package com.tnsw.noxnox;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.tnsw.coreutils.AsyncManager;
import com.tnsw.noxnox.downloader.DownloaderService;
import com.tnsw.noxnox.downloader.GCMManagerService;
import com.tnsw.noxnox.downloader.GCMReceiverInterface;
import com.tnsw.noxnox.util.JSONParameter;
import com.tnsw.noxnox.util.ServerHelper;
import com.tnsw.noxnox.util.ServerHelperListener;

public class GCMIntentService extends IntentService {

	public static boolean sIsRunning = false;
	public static GCMIntentService sInstance;
	private String tag = "GCMIntentService";
	
	public GCMIntentService() {
		super("");
		Log.d(tag, "Constructor()");
		sIsRunning = true;
		
	}
	
	public GCMIntentService(String name) {
		super(name);
		Log.d(tag, "Constructor(name=" + name + ")");
		sIsRunning = true;
	}
	
	public static GCMIntentService getInstance() {
		if (sIsRunning == false) {
			sInstance = new GCMIntentService("gcm");
		}
		
		return(sInstance);
	}
	
	
	
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	
    	Log.d(tag, tag + ":onStartCommand()");
    	GCMIntentService.sIsRunning = true;
    	sInstance = this;
    	GCMManagerService gcms = GCMManagerService.getInstance();
    	DownloaderService dls = DownloaderService.getInstance(this);
    	gcms.registerReceiver(dls);
    	this.doHandle(intent);
    	if (intent == null) {
    		Log.d(tag, "intent == null!!");
    	}
    	return START_STICKY;
    }
    
    public void doHandle(Intent intent) {
    	String value = "";
    	
    	if (intent == null) {
    		Log.e(tag, "doHandle(intent=null)");
    		return;
    	}
    	
    	if (intent.getAction() != null) {
    		if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
    			if (intent.getExtras().containsKey("unregistered")) {
    				value = intent.getExtras().getString("unregistered");
    				
    				this.unregister(value);
    				
    			} else if (intent.getExtras().containsKey("registration_id")) {
    				value = intent.getExtras().getString("registration_id");
    				Log.d(tag, "registrationId=" + value);
    				
    				this.register(value);
    			}
    			
    		} else {
    			GCMManagerService gcms = GCMManagerService.getInstance();
    			gcms.broadcast(intent);
    			
    		}
    		
    	} else {
    		Log.w(tag, "intent.getAction() is null, do nothing");
    	}

    }
	
	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d(tag, "onHandleIntent()");
	}
	
	public void unregister(String packageName) {
		Log.d(tag, "unregister(" + packageName + ")");
		ArrayList<NameValuePair> a = new ArrayList<NameValuePair>();
		a.add(new BasicNameValuePair("cmd", "unregister"));
		
		AsyncManager asyncManager = AsyncManager.getInstance();
		
		asyncManager.appendNetworkLog("http://172.16.50.192/PredictWeb/GCM.ashx", a);
	}
	
	public void register(String registrationId) {
		Log.d(tag, "register(" + registrationId + ")");
		final SharedPreferences settings = this.getSharedPreferences("GCM", 0);
		
		String newRegId = registrationId;
		String prevRegId = "";
		
		if (settings != null) {
			prevRegId = settings.getString("registration_id", "");
			
			SharedPreferences.Editor editor = settings.edit();
		    editor.putString("registration_id", registrationId);
		    editor.putLong("last_upd", System.currentTimeMillis());
		    editor.commit();	
		    
		    Log.d(tag, "Committed registration_id=" + registrationId);
		   
		} else {
			Log.e(tag, "SharePref is null");
		}
		
		if ( (newRegId.equals(prevRegId) == false) || (settings.getLong("primarykey", -1l) == -1l) ) {
			// registration_id is changed or do not have primarykey
			
			ArrayList<JSONParameter> a = new ArrayList<JSONParameter>();
			a.add(new JSONParameter("uniqueid", newRegId));
			a.add(new JSONParameter("os_type", 1));
			a.add(new JSONParameter("os_version", android.os.Build.VERSION.RELEASE));

			ServerHelper sh = new ServerHelper(this, "register", a, new ServerHelperListener() {
				
				@Override
				public void onComplete(ServerHelper sender, Long result, String jsonStr, JSONObject jsonObj, String command, String tranid) {
					Log.d("helper", "onComplete, result=" + String.valueOf(result) + ", command=" + command + ", tranid=" + tranid);
					try {
						JSONObject arguments = (JSONObject) jsonObj.get("arguments");
						long primarykey = arguments.getLong("primarykey");
						Log.d(tag, "primarykey=" + primarykey);
						
						if (settings.getLong("primarykey", -1l) == -1l) {
							SharedPreferences.Editor editor = settings.edit();
						    editor.putLong("primarykey", primarykey);
						    editor.commit();
						    Log.d(tag, "committed primarykey=" + primarykey);
						}
					} catch (Exception e) {
						Log.e(tag, "onComplete - " + e.toString(), e);
					}
					
					
				}
			});
			
			sh.run();
			
		} else {
			Log.d(tag, "Not connect to TNSW server because primarykey exists / registraion_id not changed");
		}

	}

}
